package com.htht.smartschool.util.system;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.htht.smartschool.model.card.TFamilyphone;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class Freemark {
	public Freemark(File templatePath) {
		try {
			configuration = new Configuration();
			configuration.setDefaultEncoding("utf-8");
			configuration.setDirectoryForTemplateLoading(templatePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
	private Configuration configuration;
	private String templateName;
	private String fileName;
	private String filePath;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public boolean createFile(List<TFamilyphone> list) {
		boolean flag = false;
		Template t = null;  
		try {
			//获取模板信息
			t = configuration.getTemplate(templateName);
		} catch (IOException e) {  
	        e.printStackTrace();  
	    }  
	          
	    File outFile = new File(filePath+fileName);  
	    Writer out = null;  
	    try {  
	        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        }  
        Map map = new HashMap<String, Object>();
        map.put("phones", list);
        try {  
            //输出数据到模板中，生成文件。  
            t.process(map, out);  
            out.close();  
            flag = true;
        } catch (TemplateException e) {  
        	flag = false;
            e.printStackTrace();  
        } catch (IOException e) {  
        	flag = false;
            e.printStackTrace();  
        }  		
        return flag;
	}
	
}
